﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.QandA;
using TomNet.IMSC.Model.DbModels.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Controllers.QandA
{
    [Description("广告")]
    [GlobalAuthorization]
    public class AdvertisementController : BaseController
    {
        public IAdvertisementContract AdvertisementContract { get; set; }
        public IModuleContract ModuleContract { get; set; }
        public IDynamicModelContract DynamicModelContract { get; set; }
        #region 列表
        [Description("广告-列表")]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult IndexAsync(int pageIndex, int pageSize, string search = "", int ModuleID = 0, int DynamicID = 0, int AdvertisementType = 0)
        {
            var query = AdvertisementContract.TrackEntities.Where(m => !m.IsDeleted);

            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Text.Contains(search));
            }

            if (ModuleID != 0)
            {
                query = query.Where(m => m.ModuleID == ModuleID);
            }

            if (DynamicID != 0)
            {
                query = query.Where(m => m.DynamicID == DynamicID);
            }

            if (AdvertisementType != 0)
            {
                query = query.Where(m => m.AdvertisementType == AdvertisementType);
            }

            var list = from q in query
                       select new
                       {
                           Id = q.Id,
                           ModuleID = (from md in ModuleContract.TrackEntities where md.Id == q.ModuleID select md.Name).FirstOrDefault(),
                           DynamicID = (from dy in DynamicModelContract.TrackEntities where dy.Id == q.DynamicID select dy.Title).FirstOrDefault(),
                           AdvertisementType = q.AdvertisementType == 1 ? "文字广告" : "图片广告",
                           Text = q.Text,
                       };



            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            list = list.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            list = total > 0 ? list.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : list;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = list.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion 
         
        #region 添加
        [Description("广告-添加")]
        public ActionResult Insert()
        {
            Inner();
            return View();
        }
        [HttpPost]
        public ActionResult InsertAsync(Advertisement entity)
        {
            if (entity.Text==null)
            {
                entity.Text = "";
            }
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                entity.AgentID = model.AgentId;
                var count = AdvertisementContract.Insert(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "录入成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "录入失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 修改
        public ActionResult Edit(int id)
        {
            Inner();
            var entity = AdvertisementContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewBag.entity = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditAsync(Advertisement entity)
        {
            if (entity.Text == null)
            {
                entity.Text = "";
            }
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var count = AdvertisementContract.Update(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 删除
        [Description("广告-删除")]
        [HttpPost]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                AdvertisementContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new Advertisement { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion 

        #region 下拉列表 
        public void Inner()
        {
            //模块
            List<SelectListItem> GridData = new List<SelectListItem>();
            //GridData.Add(new SelectListItem { Value = "0", Text = "无" });
            var data = from m in ModuleContract.TrackEntities
                       select new SelectListItem
                       {
                           Value = m.Id + "",
                           Text = m.Name 
                       };
            GridData.AddRange(data);
            ViewBag.mentity = new SelectList(GridData);
            //动态
            GridData = new List<SelectListItem>();
            //GridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dm in DynamicModelContract.TrackEntities.Where(d => !d.IsDeleted)
                   select new SelectListItem
                   {
                       Value = dm.Id + "",
                       Text = dm.Title
                   };
            GridData.AddRange(data);
            ViewBag.dentity = new SelectList(GridData);
        }
        #endregion
    }
}